package com.zzyl.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.zzyl.constant.SuperConstant;
import com.zzyl.dto.LoginDto;
import com.zzyl.entity.SysUser;
import com.zzyl.enums.BasicEnum;
import com.zzyl.exception.BaseException;
import com.zzyl.mapper.SysUserMapper;
import com.zzyl.service.SysUserService;
import com.zzyl.vo.UserVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.util.Objects;

@Service
public class SysUserServiceImpl implements SysUserService {
    @Autowired
    private SysUserMapper sysUserMapper;
    @Override
    public UserVo login(LoginDto loginDto) {
        String username = loginDto.getUsername();
        String password = loginDto.getPassword();

        //md5加密
        password = DigestUtils.md5DigestAsHex(password.getBytes());

        SysUser sysUser = sysUserMapper.login(username);

        //账号是否存在
        if(Objects.isNull(sysUser)){
            throw new BaseException(BasicEnum.LOGIN_FAIL);
        }
        //密码是否正确
        if(!sysUser.getPassword().equals(password)){
            throw new BaseException(BasicEnum.LOGIN_FAIL);
        }

        //账号是否被禁用
        if(SuperConstant.DATA_STATE_1.equals(sysUser.getDataState())){
            throw new BaseException(BasicEnum.LOGIN_FAIL);
        }
        //账号是否被删除
        if(sysUser.getIsDelete().equals(1)){
            throw new BaseException(BasicEnum.LOGIN_FAIL);
        }
        return BeanUtil.toBean(sysUser,UserVo.class);
    }
}
